package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: reverseList3
 * @author: chanzhugang
 * @create: 2022/09/12 19:16
 */
public class ReverseList3 {

    /**
     * 206 反转链表
     * https://leetcode.cn/problems/reverse-linked-list/
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 三指针交替法, 和开辟新链表法类似
        ListNode prev = null;
        ListNode curr = head;
        ListNode next;
        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}